package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotate.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.pojo.Employee;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl  extends ServiceImpl<EmployeeMapper,Employee> implements EmployeeService  {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();//

        //1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username); //

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对从前端传过来的密码进行md5加密，并和数据库中的密码进行比对
         password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }
//新增员工
    @AutoFill(OperationType.INSERT)
    @Override
    public void add(EmployeeDTO employeeDTO) {
        //把给的数据赋值给employee对象
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        //状态为启用
        employee.setStatus(StatusConstant.ENABLE);
        //设置密码吗，默认为123456，需要md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        //创建时间、更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        //创建人、更新人。在拦截器中先设置当前登录用户id，在业务实现类里获取
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        //新增数据
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
      Page<Employee> page =employeeMapper.pagePage(employeePageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }
//更改员工状态启用或禁用
    @Override
    public void empStatus(Integer status, Long id) {

//        //查询id对应的员工
//        LambdaUpdateWrapper<Employee> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.eq(Employee::getId,id);
//        //设置更新条件
//        Employee employee = new Employee();
//        employee.setStatus(status);
//        //更新
//        employeeMapper.update(employee,wrapper);

        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.updateById(employee);
    }
//根据ID查询员工信息
    @Override
    public Employee getEmpById(Long id) {

//        LambdaQueryWrapper<Employee> queryWrapper = Wrappers.lambdaQuery(Employee.class).eq(Employee::getId, id);
//        employeeMapper.selectOne(queryWrapper);

        Employee emp = employeeMapper.selectById(id);
        return emp;
    }
    //修改员工信息
    @AutoFill(OperationType.UPDATE)
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
//        //修改业务逻辑：先删除原来的信息，再加上新修改的信息
//        //1.根据id删除原来的员工信息
//        employeeMapper.deleteById(employeeDTO.getId());
//        //2.添加新修改的员工信息
//        //把传参复制给对象，设置md5加密的默认密码123456，再insert
//        Employee employee = new Employee();
//        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        employeeMapper.insert(employee);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        employeeMapper.updateById(employee);
    }


}
